
% randomly timed steps across the entire field of view
% bcoe@biomed.queensu.ca
% required bcoe functions:
% define_colors
% standard_date(2);
% inputdlg_offscreen;
% questdlg_offscreen;
%
% 2006-nov-28 version 03 added eye tracking

clc;
clear;
close all;
clear persistent
clear global
clear mex
drawnow;

%% computer specific information
screenRect=get(0,'ScreenSize');
c_x=screenRect(3)/2;
c_y=screenRect(4)/2;

switch 7
    case exist('C:\Data\Queens_MRI\_bcoe\randomwalk','dir')% prometheus
        disp('prometheus');
        home_folder='C:\Data\Queens_MRI\_bcoe\randomwalk';
        wid=1; % window id #
        distance2screen=66;% cm
        screenwidth=37.7; %-ish  cm
    case exist('E:\_User\_bcoe\Data\randomwalk','dir')% magnet
        disp('magnet');
        home_folder='E:\_User\_bcoe\Data\randomwalk';
        wid=1; % window id #
        distance2screen=140;% cm ~140cm
        screenwidth=45; % cm 45
    case exist('yo mama randomwalk','dir')% sham
        disp('sham');
        home_folder='E:\_User\_bcoe\Data\randomwalk';
        wid=1; % window id #
        distance2screen=140;% cm ~140cm
        screenwidth=45; % cm 45
    otherwise % error
end
cd(home_folder)
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%    Global Defaults    %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%

if any(screenRect<1)
    error('screen size has been changed after opening matlab')
end
dphs=atan((screenwidth/2)/distance2screen)*180/pi;% degrees per half screen
pixperdeg=screenRect(3)/2/dphs; % pixels per degree
c=define_colors(256);
c.BACKGROUND=c.BLACK;
c.FIX=c.RED;
c.TGT=c.GREEN;
round_clock=round(clock);
walk_time_jitter=.30; % max jitter in the walk time, as a % of diff(walktime). will be adjusted to align to refreshrate
clear distance2screen screenwidth dphs screenRect
CharAvail;% call it now to load it
global OSX_JAVA_GETCHAR;

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%   ASSIGN PARAMETERS   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, try to load table of parameter names and set values
try % this should speed things along if your running a few studies on the same subject
    load('temp')
    for par = 1:size(Parameters,1)% assign each parameter in the table to its value
        eval([Parameters{par,1} '=''' Parameters{par,2} ''';']); % for string entries
    end
    fprintf('sub_inits =%s\n',sub_inits)% check if it exists and display
    fprintf('sub_code  =%s\n',sub_code)% check if it exists and display
    if ~strcmp(kyou,datestr(now,29))% check if it exists  and display & ...
        error(' ');% if today's date doesn't match the date in the temp file force 'try' to fail
    end
    file_nb=sprintf('%02d',str2num(file_nb)+1);% check if it exists & increment
    fprintf('TR        =%s\n',TR)% check if it exists and display
    fprintf('t1eq_scans=%s\n',t1eq_scans)% check if it exists and display
    fprintf('abab      =%s\n',abab)% check if it exists and display
    fprintf('max_ecc   =%s\n',max_ecc)% check if it exists and display
    fprintf('tgt_cnt   =%s\n',tgt_cnt)% check if it exists and display
    fprintf('sac_dur   =%s\n',sac_dur)% check if it exists and display
    fprintf('fix_dur   =%s\n',fix_dur)% check if it exists and display
    clc;
catch % else start from scratch
    disp(' -> loading default settings');
    pause(.5)
    sub_inits='XXX';
    sub_code='00000';
    kyou=datestr(now,29);
    file_nb='00';
    TR='5000';
    t1eq_scans='3';  %T1 equilization scans
    abab='1';
    max_ecc='8';
    tgt_cnt='40';
    sac_dur='TR*4';
    fix_dur='TR*2';
end
tgt_ecc=linspace(-str2num(max_ecc),str2num(max_ecc),str2num(tgt_cnt));

Parameters={...% variable  value           'discription'                           string or number?
    'sub_inits',	sub_inits,		'Subjects 3 Initials (ABC)',            's';...
    'sub_code',	    sub_code,		'Subjects 5 Digit MRI code (00000)',                                's';...
    %        'kyou',		    kyou,		    'Today''s Date (yyyy-mm-dd)',           's';...
    'file_nb',		file_nb,		'File # (or run #, always 2 digits):',  's';...
    %        'prescan_time',	prescan_time,	'Prescan Normalization Time (in secs, 0 = wait for MR trigger)', 'n';...
    'TR',	        TR,          	'TR (in millisecs)',                    'n';...
    't1eq_scans',	t1eq_scans, 	'# of T1 saturation scans (in TR)',     'n';...
    'abab',	        abab, 	        'ABABA, BABAB, ABAB, BABA (1, 2, 3, or 4)',              'n';...
    'max_ecc',	    max_ecc,        'max Ecc of targets across screen.'      'n';...
    'tgt_cnt',	    tgt_cnt,        ['Number of saccades across screen. ('   ' ref/sac)'] ,   'n';...
    'sac_dur',	    sac_dur,        'Duration of Saccade blocks (in ms or "TR*n" )',   'n';...
    'fix_dur',	    fix_dur,        'Duration of Fixation blocks (in ms or "TR*n" )',  'n';...
    };

save('temp','Parameters','kyou');    % saves temp data (still in string format)
%now set the numeric data to numbers
for par= find(char(Parameters{:,4})=='n')' % for numeric entries
    eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
    eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
end
clear par

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define states (video presentation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
i=1;
%S.WAIT   =i;    t_state{i}='Waiting';      i=i+1;
S.T1EQ   =i;    t_state{i}='T1 Equ';        i=i+1;
S.L_FIX  =i;    t_state{i}='Left Fixation'; i=i+1;
S.R_FIX  =i;    t_state{i}='Right Fixation';i=i+1;
S.L_WALK =i;    t_state{i}='Left Walk';     i=i+1;
S.R_WALK =i;    t_state{i}='Right Walk';    i=i+1;
S.ENDTASK=i;    t_state{i}='End-Task';      i=i+1;

%state_time(1:i-1)=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define state timing & update parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
efile_name=[Parameters{1,2}(1:3)  char(str2num(kyou(6:7))+64)  kyou(9:10)  Parameters{3,2} ]; % convert month to letter A=jan B=feb...etc
update=2;
while update
    if update==1 % skip interface the first time to do calculations
        clc;
        fprintf('Duration of Paragigm: %ims or %i:%imin.\n', max(state_end_time), floor(max(state_end_time)/60000),rem((max(state_end_time)/60000)*60,60))
        fprintf('Total # of Volumes: %g\n', max(state_end_time)/TR)
        fprintf('TR=%g, Skip: %g, Active: %g, Baseline: %g\n', TR ,t1eq_scans ,sac_dur/TR, fix_dur/TR)
        fprintf('(%g*TR)=%gms\n', max(state_end_time)/TR,(max(state_end_time)*TR)/TR);
        fprintf('%s \n','#  State:          START: FINISH: TR''s: ')
        for i=1 :length(state_queue)
            fprintf('%g: %s%s% 7g% 7g    %g\n',state_queue(i),t_state{state_queue(i)}, repmat(' ',1,length(char(t_state{:}))+1-length(t_state{state_queue(i)})), state_start_time(i), state_end_time(i), duration_o_state(state_queue(i))/TR )
        end

        cd(home_folder)
        load('temp') % gets the string versions back
        %Parameters(7,3)={['Number of targets across screen: ' num2str(length(tgt_ecc))]};
        Parameters(8,3)={['Number of saccades across screen. (' num2str((sac_dur)/((tgt_cnt)*(1000/60))) ' ref/sac)']};
        [ParamInputs update] = inputdlg_offscreen(Parameters(:,3), ['Enter Parameters - ' file_name] , 1, Parameters(:,2));
        drawnow;
        if isempty(ParamInputs);
            disp('Task Canceled');
            return
        end
        kyou=datestr(now,29);% force to todays date
        [Parameters{:,2}] = deal(ParamInputs{:});
        clear ParamInputs
        save('temp','Parameters','kyou');    % saves temp data (still in string format)
        for par=1:length(Parameters)
            if char(Parameters{par,4})=='n' % for numeric entries
                eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
                eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
            else
                eval([Parameters{par,1} '=''' Parameters{par,2} ''';']);
            end
        end
        tgt_ecc=linspace(-(max_ecc),(max_ecc),(tgt_cnt));
        % save data file
        folder=[Parameters{1,2} '.' kyou];
        if ~exist(folder,'dir')
            eval(['mkdir ' folder]);
        end
        eval(['cd ' folder]);
        file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
        if exist([file_name,'.mat'],'file')
            yesno=questdlg_offscreen(['File Exits! Overwrite ',file_name,'.mat?'],'Be Careful!','Yes','No','No');
            drawnow;
            if yesno(1)=='N'
                disp(['File Exists: ' file_name])
                update=1;
                file_nb=sprintf('%02d',str2num(file_nb)+1);% check if it exists & increment
                Parameters{3,2}=file_nb;
                cd(home_folder)
                save('temp','Parameters','kyou');    % saves temp data (still in string format)
                eval(['cd ' folder]);
            end
            clear yesno;
        end
    end % if update==1
    if update>1, update=1;end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % start do time stuff
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    number_o_block=6;
    duration_o_state(S.T1EQ)=t1eq_scans*TR;% dummy or T1Eq scans
    duration_o_state(S.L_FIX)=round(fix_dur/TR)*TR;
    duration_o_state(S.L_WALK)=round(sac_dur/TR)*TR;
    duration_o_state(S.R_FIX)=round(fix_dur/TR)*TR;
    duration_o_state(S.R_WALK)=round(sac_dur/TR)*TR;
    duration_o_state(S.ENDTASK)=0;

    state_queue=[S.T1EQ];
    switch abab
        case 1
            for i= 1:(number_o_block)/2
                state_queue=[state_queue S.L_WALK S.L_FIX S.R_WALK S.R_FIX ];
            end
            state_queue=[state_queue S.L_WALK S.L_FIX ];
        case 2
            for i= 1:(number_o_block)/2
                state_queue=[state_queue S.R_WALK S.R_FIX S.L_WALK S.L_FIX ];
            end
            state_queue=[state_queue S.R_WALK S.R_FIX ];
        case 3
            for i= 1:(number_o_block)/2
                state_queue=[state_queue S.L_WALK S.L_FIX S.R_WALK S.R_FIX ];
            end
        case 4
            for i= 1:(number_o_block)/2
                state_queue=[state_queue S.R_WALK S.R_FIX S.L_WALK S.L_FIX ];
            end
    end
    state_queue(end+1)=S.ENDTASK;
    
    state_duration=duration_o_state(state_queue);
    state_duration=state_duration(:);
    state_queue=state_queue(:);
    state_end_time=cumsum(state_duration);
    state_start_time=[0; state_end_time(1:end-1) ];
    %         [state_queue state_duration state_end_time] ;
end % while update

save('temp','Parameters','kyou')% reload at end for saving with the A structure
m_TR=num2str((max(state_end_time))/TR); %for report
walking=sac_dur/length(tgt_ecc):sac_dur/length(tgt_ecc):sac_dur;
walking(end)=sac_dur+10; %so last walk doesn't co-occure with next state onset
jitter_these=(rem(length(tgt_ecc),2)==1)+1:2:length(tgt_ecc);% jitter odd ones only if #tgts is even else even ones only
if isprime(length(jitter_these))
    jitter_these(round(length(jitter_these)/2))=[];
end
switch 0
    case rem(length(jitter_these),4)
        jittertime=repmat([-5 -3 3 5],1,length(jitter_these)/4);
    case rem(length(jitter_these),3)
        jittertime=repmat([-5 -3 5 -5 3 5],1,length(jitter_these)/3/2);
    case rem(length(jitter_these),2)
        jittertime=repmat([-3 3],1,length(jitter_these)/2);
end
clear spacea spaceb spacec spaced number_o_block Parameters kyou file_nb sub_inits par fix_dur i update sac_dur t1eq_scans abab sub_code
% eval(['cd ' home_folder]);


stim_size=.1;% radius of stim
s_circle=[-1 -1	1 1]*pixperdeg*stim_size;      						% stimulus circle
fix_b=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*(stim_size/4.5)));	% fixation middle
fix_a=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*stim_size));	% fixation circle
% Number of Locations
% 135  90  45
% 180  +  360
% 225 270 315
% angle of 0 means ecc of 0 and vice versa!
loc_AngEcc(:,2)=tgt_ecc;
loc_AngEcc(:,1)=360;
n_loc=length(loc_AngEcc);
loc_XY=[];
[ loc_XY(:,1) loc_XY(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2),1);
pixloc_XY=[];
pixloc_XY (:,1)=(loc_XY (:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
pixloc_XY (:,2)=(loc_XY (:,2)*pixperdeg)+c_y;
for i=1:n_loc
    tgt_rects(i,:)=floor([pixloc_XY(i,:) pixloc_XY(i,:)]+s_circle); % for use with mac's LeToRiBo rect shite
    tgt_cents(i,:)=tgt_rects(i,:)+(pixperdeg*stim_size)*.65*[1 1 -1 -1];
end
% debug size
% figure(1);clf;hold on
% fill(tgt_rects(1,[1 1 3 3]),tgt_rects(1,[2 4 4 2]),'c')
% fill(tgt_cents(1,[1 1 3 3]),tgt_cents(1,[2 4 4 2]),'w')
% axis([0 c_x*2 0 c_y*2])
clear pixloc_XY loc_XY loc_AngEcc stim_size s_circle

%%%%%%%%%%%%%%%%%%%%%%%
%% check if EL1K connected  %%
%%%%%%%%%%%%%%%%%%%%%%%
imode = Eyelink('IsConnected');
if imode<1; %check for dummy mode each time.
    EYELINK('shutdown');
    if eyelink('initialize') ~= 0
        button = questdlg_offscreen('eyelink is not connecting','no EL1K','exit','DUMMY mode','DUMMY mode');
        drawnow;
        if button(1)=='D'
            eyelink('initializedummy');
            imode=-1;
        else
            fprintf('COE: program exited by user\n')
            %status=0;
            return
        end
    end
end
Eyelink('StartSetup');
drawnow
if imode==1
    i = EYELINK('openfile',[efile_name,'.edf']);
    if i~=0
        disp(['COE: Cannot create EDF file: ' efile_name]);
        %EYELINK('Shutdown');
        return;
    end
    EYELINK('command', 'add_file_preamble_text', 'Recorded by BCOE');
    %   SET UP TRACKER CONFIGURATION
    eyelink('command', 'calibration_type = HV5');
    %eyelink('command', 'calibration_type = HV9');
    %	set parser (conservative saccade thresholds)
    eyelink('command', 'saccade_velocity_threshold = 35');
    eyelink('command', 'saccade_acceleration_threshold = 9500');
    %	set EDF file contents
    eyelink('command', 'file_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,MESSAGE');
    % eyelink('command', 'file_event_filter = LEFT,RIGHT,MESSAGE');
    % Sets which types of events will be written to EDF file. See tracker file
    % DATA.INI for types.
    % Arguments: <list>: list of event types
    % LEFT, RIGHT events for one or both eyes
    % FIXATION fixation start and end events
    % FIXUPDATE fixation (pursuit) state updates
    % SACCADE saccade start and end
    % BLINK blink start an end
    % MESSAGE messages (user notes in file)
    % BUTTON button 1..8 press or release
    % INPUT changes in input port lines
    eyelink('command', 'link_event_filter = LEFT,RIGHT,FIXATION,BLINK');
    % Sets which types of events will be sent through link. See tracker file
    % DATA.INI for types.
    % Arguments: <list>: list of event types
    % LEFT, RIGHT events for one or both eyes
    % FIXATION fixation start and end events
    % FIXUPDATE fixation (pursuit) state updates
    % SACCADE saccade start and end
    % BLINK blink start an end
    % MESSAGE messages (user notes in file)
    % BUTTON button 1..8 press or release

    eyelink('command', 'link_sample_data  = LEFT,RIGHT,GAZE,AREA');
    % Sets data in samples sent through link. See tracker file DATA.INI for
    % types.
    % Arguments: <list>: list of data types
    % GAZE screen xy (gaze) position
    % GAZERES units-per-degree screen resolution
    % HREF head-referenced gaze
    % PUPIL raw eye camera pupil coordinates
    % AREA pupil area
    % STATUS warning and error flags
    % BUTTON button state and change flags
    % INPUT input port data lines

end

%% start screen things for calibration or drift correct
FlushEvents
Screen('Preference', 'VisualDebuglevel', 3); % 4 is default but it makes a painful white screen
%Screen('Preference', 'ConserveVRAM',0);

[w,screenRect] = SCREEN('OpenWindow',wid);
hza=Screen('FrameRate',w);
hzn=Screen('NominalFrameRate',w);
jittertime=jittertime*1000/hzn; % calculate the jitter time by the refreshrate

SCREEN('fillrect',w,c.BACKGROUND);
SCREEN('flip',w);
SCREEN('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN('TextSize',w,40);
disp(' ');
disp(' ');
disp(' ');
el=EyelinkInitDefaults(w);
el.backgroundcolour=c.BLACK;
el.foregroundcolour=c.L_GREY;
if imode==1
    disp('COE: entering EyelinkDoTrackerSetup_bcoe');
    disp('COE:  c = calibrate ');
    disp('COE:  v = validate ');
    disp('COE:  d = drift correct ');
    disp('COE: esc= exit ');
    ttext='entering calibration mode';
    [normBoundsRect]=Screen('TextBounds',w,ttext);
    SCREEN('DrawText',w,ttext,c_x-(normBoundsRect(3)/2),c_y-100,c.D_GREY);
    SCREEN('flip',w);
    pause(2);
    err=EyelinkDoTrackerSetup_bcoe(el);
    disp('COE: exiting EyelinkDoTrackerSetup_bcoe')
else
    disp('COE: skipped EyelinkDoTrackerSetup_bcoe')
    ttext='initializedummy mode';
    [normBoundsRect]=Screen('TextBounds',w,ttext);
    SCREEN('DrawText',w,ttext,c_x-(normBoundsRect(3)/2),c_y-100,c.D_GREY);
    SCREEN('flip',w);
    pause(2);
end



%% Waiting for the MRI to start

ttext='Waiting for the MRI to start';
normBoundsRect=Screen('TextBounds',w,ttext);
SCREEN('DrawText',w,ttext,c_x-(normBoundsRect(3)/2),c_y-100,c.GREEN);
SCREEN('flip',w);
i=0;
ch=[];
ListenChar(2);% shuts off keyboard output to windows
fprintf(1,['COE: ' ttext '\n'])
fprintf(1,'COE: press esc to exit\n')
drawnow
FlushEvents
kbtime=getsecs+.005;
while 1
    if getsecs>kbtime; % prevent over polling, measure once every 5ms
        kbtime=getsecs+.005;
        if OSX_JAVA_GETCHAR.getCharCount>0
            ch(end+1) = OSX_JAVA_GETCHAR.getChar;
            switch ch(end)
                case 27
                    fprintf('COE: Task aborted by user (JG)\n')
                    SCREEN('closeall')
                    ListenChar(0);% shuts off keyboard output to windows
                    return
                case 53 % ='5'
                    fprintf('COE: started\n')
                    break
                otherwise
                    ch(end)=[];
                    %fprintf([load_ascii_code(ch(end)) '\n'])
            end
        else
            [keyIsDown,secs,keyCode] = KbCheck; % (incase OSX_JAVA_GETCHAR.getCharCount fails) , however KbCheck is faster and ususally gets it first anyway
            if keyCode(27)% ESC on pcwin
                fprintf('COE: Task aborted by user (KC)\n')
                SCREEN('closeall')
                ListenChar(0);% shuts off keyboard output to windows
                return
            end
        end
        FlushEvents
    end
end
ListenChar(0);% keyboard output to windows again

%% StartRecording

ListenChar(2);% shuts off keyboard output to windows
drawnow
FlushEvents
% prepare t1_sat screen;
next_tgt=1;
index=1;
state=state_queue(index);
trial=0;
next_TR=1;
report=1;
kbtime=1;
MRI_TRIGGER=[];
HideCursor
SCREEN(w,'filloval',c.FIX,tgt_rects(next_tgt,:));  % draw next_tgt
screen('flip',w);
abs_start_time=(getsecs*1000);
ctim=(getsecs*1000)-abs_start_time; % current time in milliseconds
eyelink('message', ['COE: abs_start_time: ' num2str(abs_start_time)  ]);
state_time=[ctim state];
%abs_start_time=EYELINK('currenttime'); % EYELINK time takes 40% more time to compute
%simpleserial('write', char(state)); % for IScan
while state < S.ENDTASK
    while ctim < state_end_time(index) & state < S.ENDTASK
        if ctim>=report || ctim>=next_TR
            clc;
            fprintf('   State: %s (%i:%i)\n', t_state{state},next_tgt,n_loc);
            fprintf('%5.0f-TR: %d of %s\n',TR, ceil((ctim)/TR),m_TR );
            fprintf(' curTime:%9.1fms\n', ctim);
            fprintf('NextTime:%9.1fms\n', state_end_time(index));
            fprintf('Remaning:%9.1fms\n', (state_end_time(index)-ctim));
            ctim=(getsecs*1000)-abs_start_time; % current time in milliseconds
            if ctim>=report
                report=(ceil(ctim/1000))*1000; % once a second
            end
            if ctim>=next_TR
                next_TR=(ceil(ctim/TR))*TR;% once a TR
            end
        end
        if (state==S.L_WALK || state==S.R_WALK) & ctim>=walk_time(next_tgt)
            next_tgt=min(next_tgt+1,n_loc);
            SCREEN(w,'filloval',c.TGT,tgt_rect(next_tgt,:));  % draw new target
            SCREEN(w,'filloval',c.BACKGROUND,tgt_cent(next_tgt,:));  % draw new target center           
            SCREEN('flip',w); % should i stay or should i go, now?
            ctim=(getsecs*1000)-abs_start_time; % current time in milliseconds
            eyelink('message', sprintf('COE: t_state: %.1f (%sing) T=%8.1f ', state+.1,t_state{state}, ctim));
            state_time(end+1,:)=[ctim state+.1];
        end
        if ctim>=kbtime % check kb only once every 10 ms (not a button pressing task)
            kbtime=floor(ctim)+10;
            if OSX_JAVA_GETCHAR.getCharCount>0
                ch = OSX_JAVA_GETCHAR.getChar;
                switch ch
                    case 48+5% 5% key on pcwin
                        MRI_TRIGGER(end+1)=ctim;
                    case 27% ESC on pcwin
                        state = S.ENDTASK; % S.ENDTASK to exit
                end
            else
                [keyIsDown,secs,keyCode] = KbCheck; % (incase OSX_JAVA_GETCHAR.getCharCount fails)
                if keyCode(27)% ESC on pcwin
                    state = S.ENDTASK; % S.ENDTASK to exit
                    disp('COE: OSX_JAVA_GETCHAR.getChar failed');
                end
            end
        end
        ctim=(getsecs*1000)-abs_start_time; % current time in milliseconds
    end % while ctim < state_end_time(index) & state < S.ENDTASK
    if state < S.ENDTASK,
        index=index+1;
        state=state_queue(index);
        switch state_queue(index)  % draw this state
            case S.L_FIX % left fixation
                SCREEN(w,'filloval',c.FIX,tgt_rects(1,:));
            case S.R_FIX % right fixation
                SCREEN(w,'filloval',c.FIX,tgt_rects(n_loc,:));
            case S.L_WALK % walk to the left
                tgt_rect=flipud(tgt_rects);
                tgt_cent=flipud(tgt_cents);
                next_tgt=1;this_tgt=1;
                walk_time=walking+round(ctim);
                walk_time(jitter_these)=walk_time(jitter_these)+jittertime(randperm(length(jittertime)));
                SCREEN(w,'filloval',c.TGT,tgt_rect(next_tgt,:));
                SCREEN(w,'filloval',c.BACKGROUND,tgt_cent(next_tgt,:));  % draw new target center
            case S.R_WALK % walk to the right
                tgt_rect=tgt_rects;
                tgt_cent=tgt_cents;
                next_tgt=1;this_tgt=1;
                walk_time=walking+round(ctim);
                walk_time(jitter_these)=walk_time(jitter_these)+jittertime(randperm(length(jittertime)));
                SCREEN(w,'filloval',c.TGT,tgt_rect(next_tgt,:));
                SCREEN(w,'filloval',c.BACKGROUND,tgt_cent(next_tgt,:));  % draw new target center
        end %switch status
        if state_duration(index)>0
            SCREEN('flip',w);
        end
    end
    ctim=(getsecs*1000)-abs_start_time; % current time in milliseconds
    eyelink('message', sprintf('COE: t_state: %f (%s) T=%8.1f ', state,t_state{state} ,ctim));
    state_time(end+1,:)=[ctim state];
end % while state
%% DONE
eyelink('message', sprintf('COE: exited task T=%8.1f ', ctim));
SCREEN('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
SCREEN(w,'TextFont','Tahoma');
SCREEN('TextSize',w,58);

ttext1='Thank You';
normBoundsRect1=Screen('TextBounds',w,ttext1);
ttext2='Please Rest';
normBoundsRect2=Screen('TextBounds',w,ttext2);
for i=0:c.M_GREY % fade in to help with light adaptation
    SCREEN('fillrect',w,[i i i]);
    SCREEN('DrawText',w,ttext1,c_x-(normBoundsRect1(3)/2),c_y-100,[0 i 0]);
    SCREEN('DrawText',w,ttext2,c_x-(normBoundsRect2(3)/2),c_y,[0 i 0]);
    screen('flip',w,4);
end
waitsecs(2);
screen('closeall');w=0;
EYELINK('stoprecording');
EYELINK('closefile');
ListenChar(0);% keyboard output to windows again
ShowCursor

load('temp')
A=[];
A.file_name=file_name;
A.clock=round_clock;
A.parameters=Parameters;
A.tgt_ecc=tgt_ecc;
A.t_state=t_state;
A.pixperdeg=pixperdeg;
A.screenRect=screenRect;
A.colors=c;
A.state_queue=state_queue;
A.state_start_time=state_start_time;
A.state_end_time=state_end_time;
A.state_time_all=state_time;
state_time2=floor(state_time(rem(state_time(:,2),1)==0,:));
A.state_time=state_time2;
save([A.file_name '.mat'],'A');
status =EYELINK('receivefile',efile_name ,[file_name '.edf']);
if status>=0
    disp(['COE: file transfer problem [' num2str(status) 'k]'])
else
    disp(['COE: ' file_name ' was transferred. [' num2str(status) 'k]'])
end
delete('temp.mat');
dir('*.mat')
dir('*.edf')

%[[round(diff(state_time(:,1)-state_time(1,1)*1))/1;0] state_time(:,2)]

return



% state_time2(:,2)==state_queue
% A.state_time(:,1)-state_start_time


